import requestUrl from '../../utils/requestUtil'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //内容
    contentText:null,
    //预览图片数组
    fullBodyPicture: [],
    //上传图片组
    uploadPicture:[]
  },
  onFormSubmit(){
    const userToken = wx.getStorageSync('token')
    const uploadData = {
      "attachment": JSON.stringify(this.data.uploadPicture),
	    "context": this.data.contentText
    }
    if (uploadData.context == "" || uploadData.context == null) {
      return wx.showToast({
        title:'请填写此时感想哦',
        icon: 'none',    
      })
    }

    requestUrl.requestUrl({
      url: "/app/ph/diary/save",
      params: uploadData,
      header:{
        token:userToken
      }
    }).then((data) => {
      if (data.data.code == 0) {
          wx.switchTab({
            url: '../index/index',
          })
      }
      
    }).catch((errorMsg) => {
                
    })
  },
  afterRead(e) {
    let userToken = wx.getStorageSync('token')
    var that = this;
    const { file } = e.detail;
    // 上传完成需要更新 fileList
    const { fullBodyPicture = [] } = this.data;
    fullBodyPicture.push({ ...file, url: e.data });
    this.setData({ fullBodyPicture });
    var temp = this.data.uploadPicture;
    wx.showLoading({
      title: '正在上传..',
    })
    wx.uploadFile({
      url: 'https://nhwechart.nsb-farmall.com/app/upload',
      filePath: file.url,
      name: 'file',
      formData:{
        params:{}
      },
      header: { 
        "content-Type": "multipart/form-data;charset=utf-8",
        'token':userToken
      },
       success(res) {
         let Imgurl = JSON.parse(res.data).url;
         temp.push(Imgurl);
         that.setData({
            uploadPicture:temp
         })
          wx.hideLoading()
       },
       fail(err) {
         console.log(err);
       }
    })
    
  },
  deletePic(e) {
    // 删除临时路径数组里的对应元素
    const { fullBodyPicture = [] } = this.data;
    fullBodyPicture.splice(e.detail.index,1);
    this.setData({ fullBodyPicture });

    // 删除上传路径数组里的对应元素
    const { uploadPicture = [] } = this.data;
    uploadPicture.splice(e.detail.index,1);
    this.setData({ uploadPicture });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})